package com.pig.controller;

import com.pig.pojo.user.Admin;
import com.pig.service.AdminService;
import com.pig.util.SysResult;
import com.pig.util.SysResultLayui;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class AdminController {

    private static final String ADMIN_TICKET = "ADMIN_TICKET";
    @Autowired
    private AdminService adminService;

    /*
     * 登录
     * */

    @RequestMapping("/admin/login")
    @ResponseBody
    public SysResult login(String username, String password,HttpServletResponse response) {

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(username);
        token.setPassword(password.toCharArray());
        subject.login(token);//提交给securityManager

        //需要将数据保存到cookie中
        Cookie cookie = new Cookie("ADMIN_TICKET", username);
        cookie.setPath("/");
        cookie.setMaxAge(7 * 24 * 60 * 60); //设定有效期 7天有效 单位秒
        //cookie.setDomain("page.com");   //主要域名中由jt.com则可以共享数据
        response.addCookie(cookie);   //将数据写入客户端
        return SysResult.success();
    }

    /*
    * 登出*/


    @RequestMapping("/admin/logout")
    public String logout(String username, HttpSession session, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        Cookie cookie = new Cookie("ADMIN_TICKET", username);
        cookie.setPath("/");
        cookie.setMaxAge(0); //设定有效期 7天有效 单位秒
        //cookie.setDomain("page.com");   //主要域名中由jt.com则可以共享数据
        response.addCookie(cookie);   //将数据写入客户端

        subject.logout();
        return "redirect:/login.html";
    }



    /**分页查询展现管理员*/
    @RequestMapping("/admin/findAdminByPage")
    @ResponseBody
    public SysResultLayui findAdminByPage(int page, int limit){

        return adminService.findAdminByPage(page,limit);
    }
    /**添加管理员*/
    @RequestMapping("/admin/save")
    @ResponseBody
    public SysResultLayui<Admin> saveAdmin(Admin admin){
        Admin admin1 = adminService.FindByAdminName(admin.getUsername());
        if(null != admin1){
            return new SysResultLayui<>(201,"用户名已存在，请重新输入！",1,null);
        }
        try {
            adminService.saveAdmin(admin);
            return SysResultLayui.success();
        }catch (Exception e){
            return SysResultLayui.fail();
        }
    }
    /**根据id改变管理员状态*/
    @RequestMapping("/admin/updateAdminStatusById")
    @ResponseBody
    public SysResultLayui<Admin> updateAdminStatusById(int id,int status){
        return adminService.updateAdminStatusById(id,status);
    }
}
